<template>
  <view
    class="main-content"
    :style="{ backgroundImage: `url(${ossImg('others/2023cakeDiy/ld_bg2.png')})`,}"
  >
    <!--  规则及中奖记录   -->
    <view class="fixed-btn__group w-375px absolute top-164px right-26px flex justify-end mb-7px">
      <view class="fixed-btn">
        <image
          class="w-32px h-32px"
          :src="ossImg('others/2023cakeDiy/rule_btn.png')"
          @click.stop="onOpenDialog"
        ></image>
        <text>活动规则</text>
      </view>
      <view class="fixed-btn">
        <image
          class="w-32px h-32px"
          :src="ossImg('others/2023cakeDiy/prize_btn.png')"
          @click.stop="viewPrizeRecord"
        ></image>
        <text>中奖记录</text>
      </view>
    </view>
    <image class="w-375px h-178px" :src="ossImg('others/2023cakeDiy/ld_title_g.gif')"></image>
    <!--  标题  -->
    <image class="w-320px h-70px -mt-10px" :src="ossImg('others/2023cakeDiy/ld_2.png')"></image>
    <!--  扫码主图  -->
    <image class="w-375px h-350px -mt-10px" :src="ossImg('others/2023cakeDiy/ld_qrcode_g.gif')"></image>
    <!--  Bottom Tips 1  -->
    <view class="text-line -mt-9px mb-8px" @click="onCheck">
      <image class="w-12px h-12px" :src="ossImg(`others/2023cakeDiy/${state.agree ? 'check' : 'uncheck'}.png`)" />
      已阅读并同意<text @click.stop="onOpenDialog('rule')">活动规则</text>和<text @click.stop="onOpenDialog('privacy')">隐私声明</text>
    </view>
    <!--  按钮组  -->
    <image
      class="w-260px h-48px"
      :src="ossImg('others/2023cakeDiy/ld_btn_2.png')"
      @click.stop="handleScanCode"
    ></image>
    <image
      class="w-260px h-48px"
      :src="ossImg('others/2023cakeDiy/ld_btn_1.png')"
      @click.stop="goBuy"
    ></image>
    <!--  Bottom Tips 2  -->
    <view class="text-line mb-20px">二维码无法识别？<text @click.stop="goToWriteOff">试试手动核销</text></view>
    <!--  规则/隐私弹窗  -->
    <view v-if="ruleModalVisible" class="rule-modal">
      <image
        class="w-230px h-83px mt-60px relative z-11"
        :src="ossImg(`others/2023cakeDiy/${modalType}_title.png`)"
      ></image>
      <view class="rule-modal__body">
        <image
          class="w-20px h-20px absolute top-27px right-15px"
          :src="ossImg('others/2023cakeDiy/rule_close.png')"
          @click.stop="onCloseDialog"
        ></image>
        <scroll-view class="rule-text" :scroll-y="true">
          <image
            class="text-image"
            :class="{ 'privacy-text': modalType === 'privacy' }"
            :src="ossImg(`others/2023cakeDiy/${modalType}_content.png`)"
          ></image>
          <image
            class="service-btn"
            :src="ossImg(`others/2023cakeDiy/contract.png`)"
            @click.stop="onService"
          ></image>
        </scroll-view>
      </view>
    </view>
    <!--  去购买弹窗  -->
    <go-buy-dialog
      v-if="state.goBuyVisible"
      @close="handleCloseGoBuyModal"
    ></go-buy-dialog>
    <!--  结果弹窗  -->
    <result-dialog
      v-if="state.resultDialogVisible"
      :result-code="state.resulCode"
      @close="state.resultDialogVisible = false"
    ></result-dialog>
    <!--  联系客服不同方式  -->
    <van-action-sheet
      :show="state.contactVisible"
      :actions="actions"
      cancel-text="取消"
      @select="onAction"
      @cancel="onActionCancel"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue"
import { generateSign2, ossImg, ObjectToQueryString, message } from "@/utils/utils";
import { onHide, onLoad, onUnload, onShow } from "@dcloudio/uni-app";
import { userLogin } from "@/services/utils";
import { onShareAppMessage } from "@dcloudio/uni-app"
import { ShareConfig } from "@/campaign/pages/2023airycake/config";
import GoBuyDialog from "./components/GoBuyDialog.vue";
import ResultDialog from "./components/ResultDialog.vue";

const actions = [
  { name: '4000880325', color: '#0f40de' },
  { name: '联系客服', openType: 'contact' },
]
const locationInfo = ref({ latitude: "", longitude: "" });
const emdlz = getApp().emdlz2
const modalType = ref('rule') // privacy
const ruleModalVisible = ref(false)
const state = reactive({
  goBuyVisible: false,
  contactVisible: false,
  resultDialogVisible: false,
  resulCode: 0,
  qrcodeUrl: '',
  agree: uni.getStorageSync('CAKE_AGREE')
})

let enterTime = "";
let outTime = "";
let stayTime = "";

onLoad(options => {
  if (options.q) state.qrcodeUrl = decodeURIComponent(decodeURIComponent(options.q))
  getApp().accessLogAdd();
})

onShow(() => {
  const ended = new Date().getTime() > 1714492799000
  if (ended) {
    // 活动已结束
    setTimeout(() => {
      uni.redirectTo({
        url: '/campaign/pages/2023airycake/status?status=1'
      })
    }, 200)
  }
})

onMounted(() => {
  // 用户进入时间
  enterTime = new Date();
  console.log('-----------stayTime', '初始化了！')
  // 码有效默认跳转领取页
  setTimeout(() => {
    if (state.qrcodeUrl) handleUrlCodeSubmit(state.qrcodeUrl)
  }, 100)
})

const uploadStayTimeEvent = (evt) => {
  console.log('---------stayTimeEvt', evt)
  if (!enterTime) return
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  console.log('----------stayTime', stayTime)
  emdlz('track','event','cake_onepack_landing_page','view','view_land_page', stayTime);
}

onUnload(() => uploadStayTimeEvent('onBeforeMount'))
onHide(() => uploadStayTimeEvent('hide'))

onShareAppMessage(() => ShareConfig())

// 关闭去购买弹窗
const handleCloseGoBuyModal = () => {
  state.goBuyVisible = false
}

const onActionCancel = () => {
  if (modalType.value === 'rule') {
    emdlz('track','event','oreo_cake_onepack_campaignrule_page','click','cancel_button1','');
  }
  if (modalType.value === 'privacy') {
    emdlz('track','event','oreo_cake_onepack_policy_page','click','cancel_button','');
  }
  state.contactVisible = false
}

// 联系客服菜单点击
const onAction = e => {
  // 点击联系客服
  if (e.detail.openType === 'contact') {
    if (modalType.value === 'rule') {
      emdlz('track','event','oreo_cake_onepack_campaignrule_page','click','online_sevice1','');
    }
    if (modalType.value === 'privacy') {
      emdlz('track','event','oreo_cake_onepack_policy_page','click','online_sevice','');
    }
    return
  }
  // 点击400电话
  if (modalType.value === 'rule') {
    emdlz('track','event','oreo_cake_onepack_campaignrule_page','click','call_service1','');
  }
  if (modalType.value === 'privacy') {
    emdlz('track','event','oreo_cake_onepack_policy_page','click','call_service','');
  }
}

// 点击联系客服
const onService = () => {
  if (modalType.value === 'rule') {
    emdlz('track','event','oreo_cake_onepack_campaignrule_page','click','customer_service1','');
  }
  if (modalType.value === 'privacy') {
    emdlz('track','event','oreo_cake_onepack_policy_page','click','customer_service','');
  }
  state.contactVisible = true
}

// 点击勾选框
const onCheck = () => {
  state.agree = !state.agree
  uni.setStorageSync('CAKE_AGREE', state.agree)
  emdlz('track','event','cake_onepack_landing_page','click','agree_rules','');
}

// 点击中奖记录
const viewPrizeRecord = () => {
  emdlz('track','event','cake_onepack_landing_page','click','prize_record','');
  if (!state.agree) return message("请先同意相关协议!");
  linkTo(`/campaign/pages/2023airycake/webview?${getWebviewSearchParams({})}&source=record`);
}

// 点击手动核销
const goToWriteOff = () => {
  emdlz('track','event','cake_onepack_landing_page','click','redeem_self','');
  if (!state.agree) return message("请先同意相关协议!");
  linkTo('/campaign/pages/2023airycake/verification')
}

const goBuy = () => {
  emdlz('track','event','cake_onepack_landing_page','click','go_purchase','');
  state.goBuyVisible = true
}

const onOpenDialog = t => {
  modalType.value = typeof t === 'string' ? t : 'rule'
  if (modalType.value === 'rule') {
    if (typeof t === 'string') {
      // 点击活动规则
      emdlz('track','event','cake_onepack_landing_page','click','check_rules1','');
    } else {
      // 点击右上角活动规则
      emdlz('track','event','cake_onepack_landing_page','click','check_rules','');
    }
  } else {
    // 点击隐私声明
    emdlz('track','event','cake_onepack_landing_page','click','prolicy_rule','');
  }
  ruleModalVisible.value = true
}

const onCloseDialog = () => {
  if (modalType.value === 'rule') {
    emdlz('track','event','oreo_cake_onepack_campaignrule_page','click','close_button1','');
  }
  if (modalType.value === 'privacy') {
    emdlz('track','event','oreo_cake_onepack_policy_page','click','close_button','');
  }
  ruleModalVisible.value = false
}

const linkTo = url => uni.navigateTo({ url })

// 生成兑奖H5需要参数
const getWebviewSearchParams = (body) => ObjectToQueryString({
  'accesstoken': uni.getStorageSync("TOKEN"),
  'code': body.qrCode,
  'openid': uni.getStorageSync("OPENID"),
  'unionid': uni.getStorageSync("UNIONID"),
  'memberid': body?.memberScore?.memberId || getApp().globalData?.user?.memberScore?.memberId || '',
  'agree': 'true'
})

/**
 * 一物一码校验
 * @param url 完整奖品链接
 * @returns {Promise<void>}
 */
const handleUrlCodeSubmit = (url) => {
  uni.getLocation({
    type: "gcj02",
    success(res) {
      locationInfo.value.latitude = res.latitude;
      locationInfo.value.longitude = res.longitude;
    },
    complete: async () => {
      const body = {
        userValue: uni.getStorageSync("OPENID"),
        qrCode: url.split('/').at(-1),
        source: "Q4",
        timestamp: Date.parse(new Date()),
        lng: locationInfo.value.longitude,
        lat: locationInfo.value.latitude,
      }
      // 域名判断不对处理
      const hostnameArr = process.env.CAKE_URL.split('.')
      hostnameArr.shift()
      if (url.includes(hostnameArr.join('.')) && !url.includes(process.env.CAKE_URL)) {
        state.resulCode = 'err'
        state.resultDialogVisible = true
        return
      }
      // 没有获取到OPENID
      if (!body.userValue) {
        try {
          await getApp().getUserLoginInfo()
          const user = await getApp().getUserInfo()
          linkTo(`/campaign/pages/2023airycake/webview?${getWebviewSearchParams({ ...body, ...user })}`);
        } catch (e) {
          uni.showToast({ title: '服务器响应错误', icon: 'none' })
        }
        return
      }
      uni.request({
        url: `${process.env.CAKE_URL}/zex-qr/api/qr/validation`,
        method: "get",
        data: {
          ...body,
          ...{ sign: generateSign2(body) },
        },
        success: (result) => {
          // 码正确处理
          if (result.data.code === 200) {
            // 静默拿取微信用户的 openId 与 unionId 信息
            uni.login({
              provider: "weixin",
              success: async (loginResult) => {
                const loginParam = { type: 1, code: loginResult.code };
                const { data } = await userLogin(loginParam);
                uni.setStorageSync("TOKEN", data?.accessToken);
                uni.setStorageSync("OPENID", data?.openId);
                uni.setStorageSync("UNIONID", data?.unionId);
                getApp().emdlz2("set", "user", "openid", data?.openId);
                getApp().emdlz2("set", "user", "unionId", data?.unionId);
                // 兑奖H5
                linkTo(`/campaign/pages/2023airycake/webview?${getWebviewSearchParams(body)}`);
              },
            });
            return
          }
          // 接口报错
          if (!result?.data.code) return linkTo(`/campaign/pages/2023airycake/status?status=2`);
          // 码错误处理
          state.resulCode = result?.data?.code || 'err'
          state.resultDialogVisible = true
        },
        fail: requestErr => {
          uni.showToast({
            title: requestErr.data.message,
            icon: "none",
            duration: 2000,
          });
        }
      })
    }
  })
}

const handleScanCode = () => {
  emdlz('track','event','cake_onepack_landing_page','click','scan_campaign','');
  if (!state.agree) return message("请先同意相关协议!");
  uni.scanCode({
    success: ({ result }) => handleUrlCodeSubmit(result)
  })
}

const handleBackHome = () => {
  getApp().emdlz2('track','event','oreo_cake_onepack_landing_page','click','back_universe_times','');
  setTimeout(() => {
    uni.switchTab({ url: "/pages/home/home" })
  }, 300)
}
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

image {
  display: block;
}

.main-content {
  width: 100%;
  min-height: 100vh;
  background-color: #0263E6;
  background-position: top left;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}
.fixed-btn__group {
  flex-direction: column;
  align-items: flex-end;
  .fixed-btn {
    width: 36px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-bottom: 14px;
    text {
      color: white;
      font-size: 9px;
      margin-top: 3px;
      line-height: 1;
    }
  }
}
.text-line {
  color: white;
  display: flex;
  align-items: center;
  font-size: 11px;
  & > image {
    margin-right: 6px;
  }
  text {
    text-decoration: underline;
  }
}
.rule-modal {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .6);
    z-index: -1;
  }
  .rule-modal__body {
    width: 295px;
    height: 70%;
    overflow: scroll;
    background-color: white;
    position: relative;
    border: 4px solid #D4201B;
    border-radius: 22px;
    display: flex;
    align-items: center;
    flex-direction: column;
    box-sizing: border-box;
    margin-top: -24px;
    .rule-text {
      height: 500px;
      padding-top: 58px;
      padding-bottom: 24px;
      box-sizing: border-box;
      image {
        margin: 0 auto;
        display: block;
      }
      .text-image {
        width: 246px;
        min-height: 2470px;
        &.privacy-text {
          width: 246px;
          min-height: 3830px;
        }
      }
      .service-btn {
        width: 184px;
        height: 54px;
        margin-top: 32px;
      }
    }
  }
}
</style>
